package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import com.itheima.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/13 21:56
 * @Desc: 菜品分类管理
 */
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 查询菜品分类列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/category/page")
    public R<Page<Category>> listAll(Integer page, Integer pageSize) {
        Page<Category> categoryPage = categoryService.listAll(page, pageSize);

        return categoryPage != null ? R.success(categoryPage) : R.error("获取菜品分类列表失败");
    }

    /**
     * 修改菜品分类信息
     *
     * @param category
     * @return
     */
    @PutMapping("/category")
    public R<String> updateCategoryInfo(@RequestBody Category category) {
        int i = categoryService.updateCategoryInfo(category);

        return i != 0 ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 删除菜品分类信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/category")
    public R<String> deleteCategory(Long ids) {
        List<Dish> dishByCaregoryId = dishService.findDishByCaregoryId(ids, null, null);
        List<Setmeal> setmeatlByCategoryId = setmealService.findSetmeatlByCategoryId(ids);
        if (dishByCaregoryId.size() != 0 || setmeatlByCategoryId.size() != 0)
            return R.error("请先删除关联的菜品");

        int i = categoryService.deleteCategory(ids);

        return i != 0 ? R.success("删除成功") : R.error("删除失败");
    }

    /**
     * 添加菜品分类
     *
     * @param category
     * @return
     */
    @PostMapping("/category")
    public R<String> addCategory(@RequestBody Category category) {
        int i = categoryService.addCategory(category);

        return i != 0 ? R.success("添加菜品分类成功") : R.error("添加失败");
    }

    /**
     * 查询菜品分类列表
     *
     * @param type
     * @return
     */
    @GetMapping("/category/list")
    public R<List<Category>> listCategoryByType(Integer type) {
        List<Category> categories = categoryService.listCategoryByType(type);

        return categories != null ? R.success(categories) : R.error("操作失败");
    }
}
